﻿using ShiQuan.DataRepository;
using ShiQuan.IotDevice.Mapping;
using ShiQuan.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ShiQuan.IotDevice.Business
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BasicIotDeviceBLL<T> where T : class, new()
    {
        /// <summary>
        /// 数据上下文
        /// </summary>
        protected DbContext dbContext
        {
            get
            {
                var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["IotDeviceDb"].ConnectionString;
                return new IotDeviceDbContext(connectionString);
            }
        }
        /// <summary>
        /// 数据仓储
        /// </summary>
        protected IRepository _repository;
        /// <summary>
        /// 获取数据仓储对象
        /// </summary>
        public IRepository Repository
        {
            get
            {
                this._repository = new RepositoryFactory().BaseRepository(this.dbContext);
                return this._repository;
            }
        }
        #region 获取数据
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="pagination">分页</param>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回分页列表</returns>
        public virtual IEnumerable<T> GetPageList(Pagination pagination, string queryJson)
        {
            var expression = ShiQuan.Utility.Extensions.True<T>();
            expression = QueryStringToExpression(expression, queryJson);
            return this.Repository.FindList(expression, pagination);
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="pagination">分页</param>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回分页列表</returns>
        public virtual IEnumerable<T> GetPageList(Pagination pagination, Expression<Func<T, bool>> linq)
        {
            return this.Repository.FindList(linq, pagination);
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回列表</returns>
        public virtual IEnumerable<T> GetList(string queryJson)
        {
            var expression = ShiQuan.Utility.Extensions.True<T>();
            expression = QueryStringToExpression(expression, queryJson);
            return this.Repository.IQueryable(expression).ToList();
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回列表</returns>
        public virtual IQueryable<T> GetList(Expression<Func<T, bool>> linq)
        {
            return this.Repository.IQueryable(linq);
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public virtual T GetEntity(string keyValue)
        {
            return this.Repository.FindEntity<T>(keyValue);
        }

        /// <summary>
        /// 根据条件获取实体
        /// </summary>
        /// <param name="linq">Linq条件</param>
        /// <returns></returns>
        public virtual T FindEntity(Expression<Func<T, bool>> linq)
        {
            return this.Repository.FindEntity(linq);
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public virtual DataTable GetTable(string queryJson)
        {
            string sql = GetSQL(queryJson);
            return this.Repository.FindTable(sql);
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public virtual DataTable GetTableBySql(string sql)
        {
            //string sql = GetSQL(queryJson);
            return this.Repository.FindTable(sql);
        }
        /// <summary>
        /// 获取分页列表,返回Datatable
        /// </summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回列表</returns>
        public virtual DataTable GetPageTable(Pagination pagination, string queryJson)
        {
            string sql = GetSQL(queryJson);
            return this.Repository.FindTable(sql, pagination);
        }
        /// <summary>
        /// 获取分页列表,返回Datatable
        /// </summary>
        /// <param name="sql">查询参数</param>
        /// <returns>返回列表</returns>
        public virtual DataTable GetPageTableBySql(Pagination pagination, string sql)
        {
            //string sql = GetSQL(queryJson);
            return this.Repository.FindTable(sql, pagination);
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        public virtual void RemoveForm(string keyValue)
        {
            string[] dels = keyValue.Split(',');
            if (dels.Length > 1)
            {
                IRepository db = new RepositoryFactory().BaseRepository(dbContext).BeginTrans();
                try
                {
                    foreach (var item in dels)
                    {
                        db.Delete<T>(item);
                    }
                    db.Commit();
                }
                catch (Exception)
                {
                    db.Rollback();
                    throw;
                }
            }
            else
            {
                this.Repository.Delete<T>(keyValue);
            }
        }
        /// <summary>
        /// 保存表单（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public virtual void SaveForm(string keyValue, T entity)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                this.Repository.Update(entity);
            }
            else
            {
                this.Repository.Insert(entity);
            }
        }
        #endregion

        #region 帮助函数
        /// <summary>
        /// 生成查询表达式
        /// </summary>
        /// <param name="queryJson">查询对象</param>
        /// <returns></returns>
        protected virtual Expression<Func<T, bool>> QueryStringToExpression(Expression<Func<T, bool>> expression, string queryJson)
        {
            if (string.IsNullOrEmpty(queryJson))
                return expression;
            var queryParam = queryJson.ToJObject();
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    default: break;
                }
            }
            return expression;
        }
        /// <summary>
        /// 根据实体生成SQL
        /// </summary>
        /// <param name="queryJson">查询对象</param>
        /// <returns></returns>
        protected virtual string GetSQL(string queryJson)
        {
            StringBuilder sb = new StringBuilder();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                sb.Append(" AND " + condition + " like '%" + keyword + "%'");
            }
            return sb.ToString();
        }
        #endregion
    }
}
